<template>
  <el-dialog
    :title="editable ? 'Edit' : 'Add'"
    :visible.sync="dialogVisible"
    width="25%"
    @close="handleClose"
  >
    <el-form
      ref="form"
      :model="dataForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="Name" prop="userName">
        <el-input
          v-model="dataForm.userName"
          style="width: 250px"
          maxlength="100"
          placeholder="enter name please"
        />
      </el-form-item>
      <el-form-item label="Phone" prop="phone">
        <el-input
          v-model="dataForm.phone"
          style="width: 250px"
          maxlength="100"
          placeholder="enter phone please"
        />
      </el-form-item>
      <el-form-item label="Email" prop="email">
        <el-input
          v-model="dataForm.email"
          style="width: 250px"
          maxlength="100"
          placeholder="enter email please"
        />
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">Cancel</el-button>
      <el-button type="primary" @click="save">Save</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getUserInfo, saveUser } from '@/api/user'
export default {
  data() {
    return {
      dialogVisible: false,
      editable: false,
      dataForm: {
        userName: '',
        phone: '',
        email: ''
      },
      rules: {
        userName: [
          { required: true, message: 'name is not null', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: 'phone is not null', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: 'Failed to verify the phone number', trigger: 'blur' }
        ],
        email: [
          { required: true, message: 'email is not null', trigger: 'blur' },
          { type: 'email', message: 'Failed to verify the email', trigger: ['blur', 'change'] }]
      }
    }
  },
  methods: {
    /**
     * save the form
     */
    async save() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          const {
            id, phone, userName, email
          } = this.dataForm
          await saveUser({ id, phone, userName, email })
          this.$message({
            type: 'success',
            message: 'save success'
          })
          this.handleClose()
        }
      })
    },

    handleClose() {
      this.dialogVisible = false
      this.editable = false
      this.$refs.form.resetFields()
      this.dataForm = this.$options.data().dataForm
    },

    async show(id) {
      this.editable = !!id
      if (id) {
        const user = await getUserInfo({ id })
        Object.assign(this.dataForm, user)
      }
      this.dialogVisible = true
    }
  }
}
</script>
